package org.dromara.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.constant.MachineConstant;
import org.dromara.system.domain.SimMallCommodity;
import org.dromara.system.domain.SimUserLevel;
import org.dromara.system.domain.bo.SimMallCommodityBo;
import org.dromara.system.domain.vo.SimMallCommodityVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SimMallCommodityMapper;
import org.dromara.system.service.ISimMallCommodityService;
import org.dromara.system.service.ISimUserLevelService;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 商城商品Service业务层处理
 *
 * @author Lion Li
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimMallCommodityServiceImpl extends ServiceImpl<SimMallCommodityMapper, SimMallCommodity>
    implements ISimMallCommodityService {

    private final ISysUserService sysUserService;
    private final ISimUserLevelService simUserLevelService;


    /**
     * 查询商城商品
     *
     * @param id 主键
     * @return 商城商品
     */
    @Override
    public SimMallCommodityVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询商城商品列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商城商品分页列表
     */
    @Override
    public TableDataInfo<SimMallCommodityVo> queryPageList(SimMallCommodityBo bo, PageQuery pageQuery) {
        IPage<SimMallCommodityVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimMallCommodityVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    @Override
    public TableDataInfo<SimMallCommodityVo> listReception(SimMallCommodityBo bo, PageQuery pageQuery) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        bo.setCommodityStatus(MachineConstant.NUMBER.ONE);
        IPage<SimMallCommodityVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SimMallCommodityVo> list = baseMapper.findAll(page, bo);
        SysUserVo sysUserVo = sysUserService.selectUserById(bo.getUserId());
        List<SimUserLevel> simUserLevels = simUserLevelService.lambdaQuery().list();
        list.getRecords().forEach(t -> {
            SimUserLevel simUserLevel = simUserLevels.stream().filter(t2 -> ObjectUtil.equal(t2.getLevelNumber(), sysUserVo.getLevel())).findFirst().orElse(null);
            if (ObjectUtil.isNotNull(simUserLevel)) {
                t.setCommodityPrice(NumberUtil.add(t.getCommodityPrice(), Convert.toBigDecimal(simUserLevel.getMallAdd(), BigDecimal.ZERO)));
            }
        });
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的商城商品列表
     *
     * @param bo 查询条件
     * @return 商城商品列表
     */
    @Override
    public List<SimMallCommodityVo> queryList(SimMallCommodityBo bo) {
        LambdaQueryWrapper<SimMallCommodity> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimMallCommodity> buildQueryWrapper(SimMallCommodityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SimMallCommodity> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimMallCommodity::getId);
        lqw.eq(bo.getUserId() != null, SimMallCommodity::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getCommodityTitle()), SimMallCommodity::getCommodityTitle, bo.getCommodityTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getCommodityLogo()), SimMallCommodity::getCommodityLogo, bo.getCommodityLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getCommodityImages()), SimMallCommodity::getCommodityImages, bo.getCommodityImages());
        lqw.eq(bo.getCommodityPrice() != null, SimMallCommodity::getCommodityPrice, bo.getCommodityPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getCommodityDescription()), SimMallCommodity::getCommodityDescription, bo.getCommodityDescription());
        lqw.eq(bo.getCommodityStock() != null, SimMallCommodity::getCommodityStock, bo.getCommodityStock());
        lqw.eq(bo.getCommoditySort() != null, SimMallCommodity::getCommoditySort, bo.getCommoditySort());
        lqw.eq(bo.getCommodityStatus() != null, SimMallCommodity::getCommodityStatus, bo.getCommodityStatus());
        return lqw;
    }

    /**
     * 新增商城商品
     *
     * @param bo 商城商品
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimMallCommodityBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SimMallCommodity add = MapstructUtils.convert(bo, SimMallCommodity.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商城商品
     *
     * @param bo 商城商品
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimMallCommodityBo bo) {
        SimMallCommodity update = MapstructUtils.convert(bo, SimMallCommodity.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimMallCommodity entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商城商品信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
